package org.springframework.security.web.authentication.rememberme;

import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.controller.display.users.UserAuthApiConstant;
import com.nuanshui.heatedloan.dal.ModelUtils;
import com.nuanshui.heatedloan.extension.security.SecurityContextService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 创建SecurityContext环境
 */
public class CustomSecurityContextFilter extends SecurityContextPersistenceFilter {

    private Logger log = LoggerFactory.getLogger("access");

    @Autowired
    private SecurityContextService securityContextService;

    private String logoutUrl = "/logout";

    private List<String> loginUrl;

    public String getLogoutUrl() {
        return logoutUrl;
    }

    public void setLogoutUrl(String logoutUrl) {

        this.logoutUrl = logoutUrl;
    }

    public List<String> getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = Arrays.asList(loginUrl.split(","));
    }

    @SuppressWarnings("finally")
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        String uri = request.getRequestURI();

        log.info("requestUrl:"+uri);

        UserAgent userAgent = (UserAgent) req.getAttribute(GlobalParam.USER_AGENT);
        String safeToken = userAgent.getSafeToken();

        if (!uri.endsWith(UserAuthApiConstant.signined)) {
            securityContextService.initContext();
        }

        if (!ModelUtils.isSafeToken(safeToken)) {
            try {
                chain.doFilter(request, res);
            } finally {
                return;
            }
        }
        if (!uri.endsWith(UserAuthApiConstant.signined)) {
            request.getSession().invalidate();
            request.getSession().getId();
        }
        try {
            //进入controller
            if (getLoginUrl().contains(uri)) {
                chain.doFilter(request, res);
            } else {
                securityContextService.setUserContext(safeToken);
                chain.doFilter(req, res);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            chain.doFilter(req, res);
        } finally {

            if (uri.endsWith(logoutUrl)) {
                securityContextService.removeUserSession(safeToken);
                return;
            }

            //剔除其他用户
            //更新用户信息
            if (getLoginUrl().contains(uri) || uri.endsWith("registerBindUser")
                    || uri.endsWith("signined") || uri.endsWith("registerExecute/create")
                    || uri.endsWith("validate-dynamic-login")
                    || uri.endsWith("validate-forget-pwd")
                    || uri.endsWith("register/create")
                    || uri.endsWith("wechat/loginByPhone")) {

                //为登录处理的
                if(securityContextService.getCurrentUser()!=null)
                {
                    securityContextService.createUserSession(safeToken);
                }
            }
        }
    }
}